package com.yh.autobio.common;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;

import com.yh.autobio.AppContext;
import com.yh.autobio.api.RetrofitSingleton;
import com.yh.autobio.component.dialog.DialogHelp;
import com.yh.autobio.modules.bean.Update;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 更新管理类
 *
 * @author FireAnt（http://my.oschina.net/LittleDY）
 * @version 创建时间：2014年11月18日 下午4:21:00
 */

public class UpdateManager {

    private Update mUpdate;

    private Context mContext;

    private boolean isShow = false;

    private ProgressDialog _waitDialog;

    public UpdateManager(Context context, boolean isShow) {
        this.mContext = context;
        this.isShow = isShow;
    }

    public boolean haveNew() {
        if (this.mUpdate == null) {
            return false;
        }
        boolean haveNew = false;
        int curVersionCode = TDevice.getVersionCode(AppContext
                .getInstance().getPackageName());
        if (curVersionCode < mUpdate.getNum_version()) {
            haveNew = true;
        }
        return haveNew;
    }

    public void checkUpdate() {
        if (isShow) {
            showCheckDialog();
        }
        RetrofitSingleton.getApiService(mContext).
                upDateApp()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    Observer<Update> observer = new Observer<Update>() {
        @Override
        public void onCompleted() {
            PLog.d("s", "onCompleted");
            hideCheckDialog();
        }

        @Override
        public void onError(Throwable e) {
            PLog.d("s", e.getMessage());
            hideCheckDialog();
        }

        @Override
        public void onNext(Update update) {
            hideCheckDialog();
            mUpdate = update;
            onFinshCheck();
        }
    };

    private void onFinshCheck() {
        if (haveNew()) {
            showUpdateInfo();
        } else {
            if (isShow) {
                showLatestDialog();
            }
        }
    }

    private void showCheckDialog() {
        if (_waitDialog == null) {
            _waitDialog = DialogHelp.getWaitDialog((Activity) mContext, "正在获取新版本信息...");
        }
        _waitDialog.show();
    }

    private void hideCheckDialog() {
        if (_waitDialog != null) {
            _waitDialog.dismiss();
        }
    }

    private void showUpdateInfo() {
//        if (TDevice.getNetworkType() == TDevice.NETTYPE_WIFI) {//在wifi下强制更新
        if (mUpdate == null) {
            return;
        }
        if (mContext != null) {
            android.support.v7.app.AlertDialog.Builder dialog = DialogHelp.getConfirmDialog2(mContext, mUpdate.getDescription(), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    UIHelper.openDownLoadService(mContext, mUpdate.getDownload_url(), mUpdate.getVersion());
                }
            });
            dialog.setTitle("发现新版本");
            dialog.setCancelable(false);
            dialog.show();
        }
//        }else {
//            if (mUpdate == null) {
//                return;
//            }
//            android.support.v7.app.AlertDialog.Builder dialog = DialogHelp.getConfirmDialog(mContext, mUpdate.getDescription(), new DialogInterface.OnClickListener() {
//                @Override
//                public void onClick(DialogInterface dialogInterface, int i) {
//                    UIHelper.openDownLoadService(mContext, mUpdate.getDownload_url(), mUpdate.getVersion());
//                }
//            });
//            dialog.setTitle("发现新版本");
//            dialog.setCancelable(true);
//            dialog.show();
//        }
    }

    private void showLatestDialog() {
        DialogHelp.getMessageDialog(mContext, "已经是新版本了").show();
    }

    private void showFaileDialog() {
        DialogHelp.getMessageDialog(mContext, "网络异常，无法获取新版本信息").show();
    }
}
